from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from aip import AipOcr
from html.parser import HTMLParser
import time
import random
import demjson
import urllib3
import logging
import os

userAccount='15368274761'
userPassword="af1121113"
loginUserAccount='5306211470018'
""" 你的 APPID AK SK """
APP_ID = '11243469'
API_KEY = 'LkbGHrd9BVGtQBvMpZLCG225'
SECRET_KEY = 'Hs7z1TfNeVQFr4QOqfi69vpkXsUIO81Q'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
tryTime=20

browser = webdriver.Firefox()
#browser.implicitly_wait(10)
browser.get('http://xf.faxuan.net')
mainpage = browser.current_window_handle

logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')


def main():
    global tryTime
    global mainpage
    logging.info('mainpage-handle:%s'%(mainpage))
    while True:
        if(tryTime<=0):
            sys.exit(0)
        cookies=getCookiesKV()
        userinfo=cookies.get('loginUser')
        
        if(userinfo==None):
            logging.info("logout")
            try:
                popwin=browser.find_element_by_id('popwinContent')
            except:
                logging.info("login win")                    
                login()
            else:
                logging.info(popwin.text)
                logging.info("login error")
        else:
            logging.info("login successful")
            mainwork()
            break

        time.sleep(2)#id popwinContent


def getCookiesStr():
    cookie = [item["name"] + "=" + item["value"] for item in browser.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    return cookiestr

def getCookiesKV():
    cookie={}
    for item in browser.get_cookies():
        cookie.update({item['name']:item['value']})
    return cookie

def getCheckCode():
    http = urllib3.PoolManager()
    r=http.request(
        'GET',
        'http://xf.faxuan.net/service/gc.html?timestamp='+str(int(time.time())*1000),
        headers={'Cookie':getCookiesStr()}
        )
    img=r.data
    f=open(os.path.dirname(__file__)+"\\temp.jpg","wb")
    f.write(img)
    f.close()
    #im=Image.load(img)
    #im.show()
    options = {}
    options["language_type"] = "ENG"
    options["probability"] = "true"
    checkcodeinfo=client.basicGeneral(img,options)
    error_info=checkcodeinfo.get('error_msg')
    if(error_info!=None):
        logging.error(error_info)
        sys.exit(1)
    codestr=checkcodeinfo['words_result'][0]['words']
    logging.info(codestr)
    return codestr.replace(' ', '')
def login():
    global tryTime
    inname=browser.find_element_by_id('userAccount')
    inpwd= browser.find_element_by_id('userPassword')
    incheckcode = browser.find_element_by_id('usercheckcode')
    for i in range(tryTime):
        inname.clear()
        inpwd.clear()
        incheckcode.clear()
        inname.send_keys(userAccount)
        inpwd.send_keys(userPassword)
        code=getCheckCode()
        while len(code)!=4:
            code=getCheckCode()
        incheckcode.send_keys(code)
        browser.execute_script('bps.userloginAction()')
        time.sleep(1)#id popwinContent
        try:
            closepopwin=browser.find_element_by_id('popwinConfirm')
        except:
            return True
        else:
            actions = ActionChains(browser)
            actions.move_to_element(closepopwin)
            actions.click(closepopwin)
            actions.perform()
    sys.exit(1)
        
def openJobPage():
    if(browser.title != "课程列表"):   
        page('1')
    while True:
        time.sleep(3)
        logging.info("in while")
        try:
            lis = browser.find_elements_by_xpath("//ul[@id='page']/li/a/div/img")
        except:
            logging.info("not find page list")
        else:
            if(len(lis)>=1):
                s=random.randint(0,len(lis)-1)
                logging.info(s)
                print(browser.execute_script('return $("#page").find("img").length'))
                browser.execute_script('$("#page").find("img")[%d].click()'%(s))
                break
            
    

def getpoint():
    #time.sleep(1)
    #browser.execute_script('base.index2(0)')
    try:
        todypoint=browser.find_element_by_id("todypoint")
        allpoint=browser.find_element_by_id("todaytpoint")
        todypoint=todypoint.text
        allpoint=allpoint.text
        logging.info(todypoint)
        logging.info(allpoint)
    except:
        logging.error('首页错误')
    else:
        return (todypoint,allpoint)
def page(index):
    while True:
        try:
            browser.execute_script("base.index2(%s)"%(index))
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            time.sleep(5)
            return True

def uptime():
    time.sleep(1)
    mainpage = browser.current_window_handle
    all_handles = browser.window_handles
    for handle in all_handles:  # 遍历全部页面句柄
        if handle != mainpage:  # 判断条件
            browser.switch_to.window(handle)  # 切换到新页面
    browser.execute_script("sessionStorage.timecur=Date.now() - %d" % (random.randint(600000,900000)))
    time.sleep(1)
    browser.execute_script('location.reload()')
    while True:
        objl=tryjs("return $('#kejmc-box-id').find('a').length")
        logging.info("<a>:%s"%(objl))
        if(objl >=1 ):
            break
        else:
            time.sleep(3)
    time.sleep(3)
    tryjs("$('#kejmc-box-id').find('a')[0].click()")
    while True:
        try:
            time.sleep(5)
            browser.execute_script('sps.exitStudy(\'ware_time_num\')')
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            time.sleep(3)
            browser.execute_script("$('#popwinConfirm').click()")
            break
    browser.switch_to.window(mainpage)

def swithcNew(index):
    time.sleep(1)
    global mainpage
    all_handles = browser.window_handles
    if(len(all_handles)>index):
        browser.switch_to.window(all_handles[index])  # 切换到新页面
        logging.info("now page:%s"%(all_handles[index]))
        return True
    else:
        logging.warning("没有这个页面")
        return False

def doWork():
    swithcNew(1)
    tryjs('sps.exitStudy()') #打开练习页
    browser.execute_script("$('.coursetab.clear').find('li')[2].click()")
    js=browser.execute_script('return $("#lx-box-id").find("a").attr("href")')
    browser.execute_script(js)


def tryjs(js):
    while True:
        try:
            logging.info(js)
            r=browser.execute_script(js)
        except:
            logging.info("javascript 没有加载完")
            time.sleep(3)
        else:
            return r

def mainwork():
    #getpoint()
    openJobPage() #打开学习页面
    uptime() #更新学习时间

    openJobPage()
    doWork()

    
main()
